package DAO;

import java.sql.*;


/**
 * Created by hadoop on 17-6-13.
 * data access object
 */
public class DbDao {
    private String driver;
    private String url;
    private String user;
    private String pass;
    private Connection conn;

    //constructors
    public DbDao() {
    }

    public DbDao(String driver, String url, String user, String pass) {
        this.driver = driver;
        this.url = url;
        this.user = user;
        this.pass = pass;
    }

    private Connection getConnection() throws Exception {
        if(conn == null){
            Class.forName(driver);
            conn = DriverManager.getConnection(url,user,pass);
        }
        return conn;
    }

    private PreparedStatement createPreparesStatement(String sql, Object[] args) throws Exception{
        PreparedStatement pstmt = getConnection().prepareStatement(sql);
        for(int i=0;i<args.length;i++){
            pstmt.setObject(i+1,args[i]);
        }
        return pstmt;
    }
    public boolean insert(String sql, Object... args) throws Exception{
        PreparedStatement pstmt = createPreparesStatement(sql,args);
        return pstmt.executeUpdate() == 1;

    }

    public ResultSet query(String sql,Object... args) throws Exception{
        PreparedStatement pstmt = createPreparesStatement(sql,args);
        return pstmt.executeQuery();
    }

    public void modify(String sql,Object... args) throws Exception{
        PreparedStatement pstmt = createPreparesStatement(sql,args);
        pstmt.executeUpdate();
    }

    public void close()throws Exception{
        if(conn != null && !conn.isClosed()){
            conn.close();
        }
    }

    //直接使用Statement
    public ResultSet query(String sql) throws Exception{
        //为了直接对ResultSet的结果进行更新，需要设置ResultSet的类型和是否更新
        Statement stmt = getConnection().createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
        return stmt.executeQuery(sql);
    }

    //getter and setter
    public String getDriver() {
        return driver;
    }

    public void setDriver(String driver) {
        this.driver = driver;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getPass() {
        return pass;
    }

    public void setPass(String pass) {
        this.pass = pass;
    }
}
